import { Vue, Component } from 'vue-property-decorator';
import { TabIndex, Response, commonIndexConfig } from '@/typings';
import { Tools } from '@/utils/tools';
import commonApi from '@/api/common-api';
import { isInCountByPow } from '@/utils';
import { PermissionConfig } from '@/store/modules/common-module';

type ModuleType = 1 | 2 | 3 | 4;
interface ModuleConfig {
    id: string;
    moduleId: string;
    title: string;
    type: ModuleType;
}
interface RelationModuleDictionary {
    moduleList?: ModuleConfig[];
    reportList?: ModuleConfig[];
    webList?: ModuleConfig[];
}
const MODULE_TYPE = {
    1: 'moduleList',
    2: 'reportList',
    3: 'webList',
    4: 'externaList'
};
@Component({})
export default class indexMixins extends Vue {
    m_showTab: boolean = true;
    m_activeName: TabIndex = 'list';
    m_moduleName: string;
    m_moduleList: RelationModuleDictionary = {};
    m_layoutConfigs: commonIndexConfig = {
        tabs: [
            {
                label: '列表',
                value: 'list',
                lang: 'layout.tabs.list'
            },
            {
                label: '详情',
                value: 'detail',
                lang: 'layout.tabs.detail'
            }
        ]
    };
    created() {
        this.m_moduleName = JSON.parse(JSON.stringify(this.$route.meta.moduleId));
        this.$nextTick(() => {
            this.m_getRelationModuleData();
            this.m_getModulePermissionData();
        });
    }
    m_changeTab(tabName: TabIndex) {
        this.m_activeName = tabName;
        // ;(this as any).SET_ACTIVENAME(tabName)
        this.$store.commit(`${this.m_moduleName}/SET_ACTIVENAME`, tabName);
    }
    // 获取相关模块接口
    async m_getRelationModuleData() {
        const res = await this._get({
            url: `${commonApi.getRelationModuleId}`,
            params: {
                moduleId: this.m_moduleName
            }
        });
        if (res.code === 0) {
            const data = res.data.map;
            for (const k in data) {
                const key = MODULE_TYPE[k];
                this.$set(this.m_moduleList, key, data[k]);
            }
        }
    }
    async m_getModulePermissionData() {
        const res = await this._post({
            url: `${commonApi.getModulePermiss}/${this.m_moduleName}`
        });
        if (res.code === 0) {
            const data: any[] = res.data.moduleAuthority;
            const permissionObj: PermissionConfig = {
                action: [],
                page: { browse: [], edit: [] },
                fields: { browse: [], edit: [], field: [] }
            };
            data.forEach((item) => {
                if (item.type === 'Action' && item.authority.length) {
                    item.authority.forEach((item) => {
                        if (item.value === 1 || item.value === -1) {
                            permissionObj.action.push(item.key);
                        }
                    });
                }
                if (item.type === 'Page' && item.authority.length) {
                    this.m_setPermission(item.authority, 'page', permissionObj);
                }
                if (item.type === 'Field' && item.authority.length) {
                    this.m_setPermission(item.authority, 'fields', permissionObj);
                }
            });

            console.log('权限集合', permissionObj);
            if (this.$store.state[this.m_moduleName]) {
                this.$store.commit(`${this.m_moduleName}/SET_PERMISSION`, permissionObj);
            }
        }
    }
    m_setPermission(authorityArr: any[], permissionKey: string, permissionObj: PermissionConfig) {
        authorityArr.forEach((authority) => {
            // 如果是字段权限则把所有的字段加上
            if (permissionKey === 'fields') {
                !permissionObj[permissionKey]['field'].includes(authority.key) && permissionObj[permissionKey]['field'].push(authority.key);
            }
            // -1 全部
            if (authority.value === -1) {
                for (const k in permissionObj[permissionKey]) {
                    permissionObj[permissionKey][k].push(authority.key);
                }
            } else {
                authority.authValue.forEach((o) => {
                    if (isInCountByPow(authority.value, o.value)) {
                        permissionObj[permissionKey][o.key].push(authority.key);
                        // 如果有编辑权限就有浏览权限
                        if (o.key === 'edit') {
                            permissionObj[permissionKey]['browse'].push(authority.key);
                        }
                    }
                });
            }
        });
    }
    m_formatDataSelect(data) {
        const selectData = data;
        for (const k in selectData) {
            selectData[k] ? Tools.setValueAndName(selectData[k]) : delete selectData[k];
        }
        this.$store.commit(`${this.m_moduleName}/SET_SELECT_DATA`, selectData);
    }
    async m_getConfig(url: string) {
        const res: Response<any[]> = await this._get({
            url,
            params: {
                moduleId: this.m_moduleName
            }
        });
        if (res.code === 0) {
            const data = res.data;
            this.m_formatDataSelect(data);
        }
    }
}
